﻿using KAs.Application.Contract.Dto;
using KAs.Common.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace KAs.Filter;

/// <summary>
/// 异常过滤器
/// </summary>
/// <remarks>
/// 异常集中处理，构建对象返回
/// </remarks>
public class ExceptionFilter : IAsyncExceptionFilter
{
    public Task OnExceptionAsync(ExceptionContext context)
    {
        if (context.ExceptionHandled == false)
        {
            ApiResult<object> apiResult;
            if (context.Exception.GetType() == typeof(BusinessException))
            {
                var thisException = (BusinessException)context.Exception;
                apiResult = ApiResult<object>.IsError(thisException.Message, thisException.Code);
            }
            else
            {
                apiResult = ApiResult<object>.IsError(
                context.Exception.InnerException != null ?
                context.Exception.InnerException.Message
                : context.Exception.Message);
            }
            context.Result = new JsonResult(apiResult);
        }
        context.ExceptionHandled = true;

        return Task.CompletedTask;
    }
}